import numpy as np
import cv2

#读取图像
img = cv2.imread('../../image/method_mopian/3.jpg')
img_muban = cv2.imread('../../image/method_mopian/3muban.jpg')
img_H, img_W, img_CH = img.shape
img_muban_h, img_muban_w, img_muban_ch = img_muban.shape
print(img.shape)
print(img_muban.shape)

scale = 0.25

#缩放图像
img_resize = cv2.resize(img,dsize=(int(img_W*scale), int(img_H*scale)))
img_muban_resize = cv2.resize(img_muban,dsize=(int(img_muban_w*scale), int(img_muban_h*scale)))
print(img_resize.shape)
#粗定位
#1.模板匹配
h, w, ch = img_muban_resize.shape
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
method = eval(methods[0])# Apply template Matching
print(method)
res = cv2.matchTemplate(img_resize,img_muban_resize,method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
    top_left = min_loc
else:
    top_left = max_loc
    print(111)
bottom_right = (top_left[0] + w, top_left[1] + h)
print(top_left, bottom_right)
cv2.rectangle(img_resize,top_left, bottom_right, 255, 10)
top_left_ = (int(top_left[0]/scale), int(top_left[1]/scale))
bottom_right_ = (int(bottom_right[0]/scale), int(bottom_right[1]/scale))
cv2.rectangle(img, top_left_, bottom_right_, 255, 10)
img_obj = img[top_left_[1]:bottom_right_[1], top_left_[0]:bottom_right_[0]]



cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.resizeWindow('image', 1000, 600)
cv2.imshow('image', img)

cv2.namedWindow('image_resize', cv2.WINDOW_NORMAL)
cv2.resizeWindow('image_resize', 1000, 600)
cv2.imshow('image_resize', img_resize)

cv2.namedWindow('image_obj', cv2.WINDOW_NORMAL)
cv2.resizeWindow('image_obj', 1000, 600)
cv2.imshow('image_obj', img_obj)

cv2.waitKey(0)